let ws = null
let listeners = []

export function connectWebSocket(userId) {
  if (ws) ws.close()
  ws = new WebSocket(`ws://localhost:9000/ws/chat/${userId}`)
  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    listeners.forEach(fn => fn(msg))
  }
  ws.onclose = () => {
    setTimeout(() => connectWebSocket(userId), 2000)
  }
}

export function onMessage(fn) {
  listeners.push(fn)
}

export function sendMessage(msg) {
  console.log('ws发送消息：', msg)
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(msg))
  } else {
    console.error('WebSocket未连接')
  }
} 